<template>
  <div id="detail">
    <detail-nav-bar ref="detailNavBar" @titleClick="titleClick">
      <div slot="center">详情页</div>
    </detail-nav-bar>
    <!-- 滚动区 -->
    <scroll
      class="detail-scroll"
      ref="scroll"
      :probeType="3"
      @scroll="detailScroll"
    >
      <!-- 轮播图 -->
      <detail-swiper :banners="banners" />
      <!-- 商品基本信息 -->
      <detail-base-info :goods="goods" />
      <!-- 店铺信息 -->
      <detail-shop-info :shop="shop" />
      <!-- 商品详情 -->
      <detail-goods-info :detailInfo="detailInfo" @imageLoad="imageLoad" />
      <!-- 商品参数 -->
      <detail-param-info ref="params" :paramInfo="paramInfo" />
      <!-- 评论 -->
      <detail-comment-info ref="comment" :commentInfo="commentInfo" />
      <!-- 推荐 -->
      <goods-list ref="recommend" :goods="recommends" />
    </scroll>
    <!-- 返回顶部按钮 -->
    <back-top v-show="isShowBackTop" @click.native="backTop" />
    <!-- 底部bar -->
    <detail-bottom-bar @addToCart="addToCart" />
  </div>
</template>

<script>
import { debounce } from "xb-js-utils";
import { mapActions } from "vuex";

import Scroll from "components/common/scroll/Scroll";

import GoodsList from "components/content/goods/GoodsList";

import DetailNavBar from "./childComps/DetailNavBar";
import DetailSwiper from "./childComps/DetailSwiper";
import DetailBaseInfo from "./childComps/DetailBaseInfo";
import DetailShopInfo from "./childComps/DetailShopInfo";
import DetailGoodsInfo from "./childComps/DetailGoodsInfo";
import DetailParamInfo from "./childComps/DetailParamInfo";
import DetailCommentInfo from "./childComps/DetailCommentInfo";
import DetailBottomBar from "./childComps/DetailBottomBar";

import { itemListener, backTop } from "common/mixin";

import {
  getDetail,
  Goods,
  Shop,
  GoodsParam,
  getRecommend
} from "network/detail";

export default {
  name: "Detail",
  components: {
    Scroll,
    GoodsList,
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    DetailBottomBar
  },
  data() {
    return {
      iid: null,
      banners: [],
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [],
      getThemeTopY: null
    };
  },
  mixins: [itemListener, backTop],
  created() {
    // 保存传入的iid
    this.iid = this.$route.query.iid;
    // 请求详情数据
    getDetail(this.iid).then(res => {
      const data = res.result;
      // 1.获取顶部轮播图
      this.banners = res.result.itemInfo.topImages;
      // 2.获取商品基本信息
      this.goods = new Goods(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );
      // 3.获取店铺信息
      this.shop = new Shop(data.shopInfo);
      // 4.商品详情数据
      this.detailInfo = data.detailInfo;
      // 5.获取参数信息
      this.paramInfo = new GoodsParam(
        data.itemParams.info,
        data.itemParams.rule
      );
      // 评论
      if (data.rate.cRate !== 0) {
        this.commentInfo = data.rate.list[0];
      }
    });
    // 请求推荐数据
    getRecommend().then(res => {
      this.recommends = res.data.list;
    });
    /**
     * themeTopYs：存储展示各个标题需要滚动的值的数组；
     * getThemeTopY：为themeTopYs数组赋值
     */
    this.getThemeTopY = debounce(() => {
      this.themeTopYs = [];
      this.themeTopYs.push(0);
      this.themeTopYs.push(-this.$refs.params.$el.offsetTop);
      this.themeTopYs.push(-this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(-this.$refs.recommend.$el.offsetTop);
    }, 20);
  },
  destroyed() {
    // 取消全局事件的监听
    this.$bus.$off("goodsItemImgLoad", this.itemImgListener);
  },
  methods: {
    // 将actions中的方法映射到组件的methods中
    ...mapActions(["a_AddToCart"]),
    imageLoad() {
      this.$refs.scroll.refresh();
      this.getThemeTopY();
    },
    titleClick(index) {
      this.$refs.scroll.scrollTo(0, this.themeTopYs[index], 200);
    },
    detailScroll(position) {
      // 返回顶部
      this.showBackTopListener(position);
      /**
       * 实现：根据滚动的位置将对应的标题设置为选中状态；
       * 原理：判断当前的滚动值所处的范围
       */
      const positionY = position.y;
      for (let i = 0; i < this.themeTopYs.length; i++) {
        // 当DetailNavBar组件中curIndex的值不等于i时才会进行判断，优化了代码
        if (this.$refs.detailNavBar.curIndex !== i) {
          // 若当前的位置和此轮循环中的i匹配则将i赋值给DetailNavBar组件中的curIndex属性
          if (this.eqThemeTopY(positionY, i)) {
            this.$refs.detailNavBar.curIndex = i;
          }
        }
      }
    },
    /**
     * y:当前的position.y的值；
     * index:当前循环到的i的值；
     * 实现：判断当前的position.y的值与themeTopYs的特定元素值的大小关系（要注意值的正负号），并返回一个boolean值
     */
    eqThemeTopY(y, index) {
      // 当处于最后一轮循环时，只需要判断scroll.y的值是否小于themeTopYs中最后一个元素值即可
      if (index === this.themeTopYs.length - 1) {
        return y <= this.themeTopYs[index];
      } else {
        // 若不是最后一轮循环，则需要判断scroll.y是否处于themeTopYs两个元素值的中间
        return y <= this.themeTopYs[index] && y >= this.themeTopYs[index + 1];
      }
    },
    addToCart() {
      /**
       * 添加到购物车：
       */
      // 整合展示购物车需要的数据
      console.log("addToCart");
      const product = {};
      product.image = this.banners[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;
      product.checked = false;

      // this.$store.dispatch("addToCartActions", product);
      // 使用了mapActions后可替换为以下代码;
      this.a_AddToCart(product).then(res => {
        console.log(res);
      });
    }
  }
};
</script>

<style scoped>
#detail {
  height: 100vh;
  position: relative;
  z-index: 9;
  background: #fff;
}
.detail-scroll {
  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
  overflow: hidden;
}
</style>
